package com.erpoa.service.impl;

import com.erpoa.annotation.DataBase;
import com.erpoa.constants.DataSourceNames;
import com.erpoa.entity.PackMessageByWuLiu;
import com.erpoa.mapper.CarProgressMapper;
import com.erpoa.service.CarProgressService;
import com.erpoa.utils.PDAException;
import com.erpoa.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chenjimin
 * @Title: CarProgressServiceImpl
 * @ProjectName oaerp
 * @Description: TODO
 * @date 2020/11/215:02
 */
@Service
public class CarProgressServiceImpl implements CarProgressService {
    private static final Logger logger = LoggerFactory.getLogger(CarProgressServiceImpl.class);
    @Autowired
    private CarProgressMapper CarProgressMapper;

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public HashMap selectByTrayNo(PackMessageByWuLiu packMessage) {
        String carNo = packMessage.getCrashLog();
        if (!isCarNo(carNo)) {
            throw new PDAException("当前车牌号有误，请确认正确的托盘号！");
        }

        String traynumber = packMessage.getTrayNumber();
        if (StringUtil.isEmpty(traynumber)) {
            throw new PDAException("无托盘号！");
        }
        HashMap returnmap = new HashMap();
        //先查询是否已装车
        int hasentruck = this.CarProgressMapper.countByTrayNo(traynumber);

        HashMap temp = this.CarProgressMapper.selectByTrayNo(traynumber);
        if (StringUtil.isEmpty(temp)) {
            throw new PDAException("当前托盘号无数据！");
        }
        returnmap.put("CUSTNAME", temp.get("CUSTNAME"));
        returnmap.put("COUNT", temp.get("COUNT"));
        returnmap.put("DEFOUTDATE", temp.get("DEFOUTDATE"));
        if (hasentruck > 0) {
            returnmap.put("RES", "当前托盘已装车");
            String descall = this.CarProgressMapper.countdescAllbydefoutdate(temp.get("CUSTNAME").toString(), temp.get("DEFOUTDATE").toString());
            returnmap.put("DESCALL", descall);
            String hasscan = this.CarProgressMapper.counthasscanBysnamedate(temp.get("CUSTNAME").toString(), temp.get("DEFOUTDATE").toString());
            returnmap.put("HASSCAN", hasscan);
            // returnmap.put("SURPLUS",Integer.valueOf(descall)-Integer.valueOf(hasscan));

            // returnmap.put("HASPROGRESS",ADivideBPercent(new BigDecimal(hasscan),new BigDecimal(descall)));


            BigDecimal hasscantemp = new BigDecimal(hasscan);
            BigDecimal descalltemp = new BigDecimal(descall);
            returnmap.put("SURPLUS", descalltemp.subtract(hasscantemp).setScale(2, BigDecimal.ROUND_HALF_UP));
            returnmap.put("HASPROGRESS", ADivideBPercent(hasscantemp.setScale(2, BigDecimal.ROUND_HALF_UP), descalltemp.setScale(2, BigDecimal.ROUND_HALF_UP)));

        }
        return returnmap;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public HashMap addtraynumber(PackMessageByWuLiu packMessage) {
        String carNo = packMessage.getCrashLog();
        if (!isCarNo(carNo)) {
            throw new PDAException("当前车牌号有误，请确认正确的托盘号！");
        }
        String traynumber = packMessage.getTrayNumber();
        if (StringUtil.isEmpty(traynumber)) {
            throw new PDAException("托盘号丢失，请重试！");
        }
        String sname = packMessage.getsName();
        if (StringUtil.isEmpty(sname)) {
            throw new PDAException("客户数据丢失，请重试！");
        }

        String defoutdate = packMessage.getDefOutDate();
        if (StringUtil.isEmpty(defoutdate)) {
            throw new PDAException("预出日期丢失，请重试！");
        }
        String count = packMessage.getJobnum();


        HashMap returnmap = new HashMap();
        int hasinsert = this.CarProgressMapper.inserttrayNumber(traynumber, count, sname, packMessage.getUser().getsCode(), defoutdate, carNo);
        if (hasinsert <= 0) {
            throw new PDAException("增加失败，请重试！");
        }
        String descall = this.CarProgressMapper.countdescAllbydefoutdate(sname, defoutdate);
        returnmap.put("DESCALL", descall);
        String hasscan = this.CarProgressMapper.counthasscanBysnamedate(sname, defoutdate);
        returnmap.put("HASSCAN", hasscan);

        BigDecimal hasscantemp = new BigDecimal(hasscan);
        BigDecimal descalltemp = new BigDecimal(descall);
        returnmap.put("SURPLUS", descalltemp.subtract(hasscantemp).setScale(2, BigDecimal.ROUND_HALF_UP));
        returnmap.put("HASPROGRESS", ADivideBPercent(hasscantemp.setScale(2, BigDecimal.ROUND_HALF_UP), descalltemp.setScale(2, BigDecimal.ROUND_HALF_UP)));
        return returnmap;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<HashMap> getCarNo(PackMessageByWuLiu packMessage) {
        List<HashMap> returmap = new ArrayList<>();
        List<HashMap> listtemp = this.CarProgressMapper.getCarNo();
        if (StringUtil.isEmpty(listtemp)) {
            throw new PDAException("未拉取到近两天的车牌号！");
        }
        for (int i = 0; i < listtemp.size(); i++) {
            HashMap map = new HashMap();
            // map.put("ID",i);
            map.put("NAME", listtemp.get(i).get("CARCODE"));
            map.put("CODE", "");

            returmap.add(map);
        }

        return returmap;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional()
    public List<HashMap> selectuntrayNum(PackMessageByWuLiu packMessage) {
        List<HashMap> detailByFplanids = CarProgressMapper.selectuntrayNum(packMessage.getsName());
        if (StringUtil.isNotEmpty(detailByFplanids)) {
            return detailByFplanids;
        }
        throw new PDAException("没有任何托盘号！");
    }


    /**
     * a / b   计算百分比
     *
     * @param a
     * @param b
     * @return eg:65.32%
     */
    public static String ADivideBPercent(BigDecimal a, BigDecimal b) {
        String percent =
                b == null ? "-" :
                        b.compareTo(new BigDecimal(0)) == 0 ? "-" :
                                a == null ? "0.00" :
                                        a.multiply(new BigDecimal(100)).divide(b, 2, BigDecimal.ROUND_HALF_UP) + "";
        return percent;
    }


    public static boolean isCarNo(String carNo) {
        Pattern p = Pattern.compile("^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(?:(?![A-Z]{4})[A-Z0-9]){4}[A-Z0-9挂学警港澳]{1}$");
        Matcher m = p.matcher(carNo);
        if (!m.matches()) {
            return false;
        }
        return true;
    }
}
